import {GenCfg} from "./GenCfg";
import {MapString, sdf} from "../expressExt/public/sdf";
import * as fs from "fs";
import {GenCode} from "../expressExt/GenCode";
import {Meta} from "../expressExt/public/Meta";
import {Menu} from "../expressExt/Menu";

export class ajaxApi {

    static imports: MapString<boolean> = {};
    static fileText = "";

    static genFile(url: string, modReq: {new(): any}, resp: any, notPost: string) {

        //收尾
        if (url == null) {
            let apiFile = Menu.root + "/" + GenCfg.codeOutMenu + "/kt/api.ts";

            let imports = "";
            for (let k in ajaxApi.imports) {
                imports += k + "\r\n";
            }
            imports += `
import {apiCRUD} from "./view/temp/apiCRUD";
            
export class api {

${ajaxApi.fileText}

}
`;
            fs.writeFile(apiFile, imports);
            return;
        }

        let reqClass = sdf.getFuncName(modReq);
        ajaxApi.imports[`import {${reqClass}} from "../modReq/${reqClass}";`] = true;

        //接口注释
        let apiComment = GenCode.readComment(GenCfg.expFuncStr, url, GenCfg.ExpressExtCommentPos);
        //下划线式接口名
        let nameUrl = GenCode.fixUrl(url)
        //驼峰式接口名
        let apiName = GenCode.fixNmaeUpperCase(nameUrl);

        ajaxApi.fileText += `
    /**
     * ${apiComment}
     * @param req
     */
    static ${apiName}(req: ${reqClass}) {
        return apiCRUD.ajax<${ajaxApi.getObjType(resp)}>("${url}").sendJSON(req, ${notPost});
    }
    
`;
    }


    static getObjType(obj: any) {
        let ret = "any";

        if (obj == null)
            return ret;

        if (typeof obj == "string" || obj instanceof String) {
            return "string";
        }

        if (obj instanceof Array) {
            return ajaxApi.getObjType(obj[0]);
        }


        if (typeof obj == "object") {
            ret = ""
            let parent = Meta.getParent(obj.constructor);
            if (parent.length > 0) {
                parent.forEach(it => {
                    let name = sdf.getFuncName(it);
                    ajaxApi.imports[`import {${name}} from "../models/${name}";`] = true;
                    ret += name + "&"
                })
                ret = ret.removeLast();
                return ret;
            }
            let name = sdf.getFuncName(obj.constructor);
            ajaxApi.imports[`import {${name}} from "../models/${name}";`] = true;
            return name;
        }


        return ret;
    }
}